# coding:utf-8
from pangolin.common.db_operateCommon import DbOperateClass
import os


def query_from_cpa_timer():
    db_operate = DbOperateClass()
    sql = "select timer.task_id,timer.timer_param,timer.timer_granularity,timer.granularity_value,timer.create_time,timer.timer_id from cpa_timer timer where  timer.timer_type='PYTHON' and timer.timer_status = '1'"
    (fc, count) = db_operate.select_by_sql(sql)
    for row in fc:
        task_id = row[0]
        timer_param = row[1]
        timer_granularity = row[2]
        granularity_value = row[3]
        create_time = row[4]
        timer_id = row[5]
        company_code, spider_name = query_from_cpa_config(timer_param)
        sql = "SELECT timer.timer_status FROM cpa_timer timer WHERE timer.timer_id = '" + timer_id + "'"
        data = db_operate.select_one_by_sql(sql)
        if data[0] is not None and data[0] == '1':
            cmd = "python " + os.path.split(os.path.realpath(__file__))[0] + "/main.py" + " " + granularity_value + \
                  " " + str(company_code) + " " + task_id + " " + str(create_time) + " " + str(spider_name) + " " + \
                  timer_param + " " + timer_granularity + " " + timer_id
            os.system(cmd)
        else:
            pass

def query_from_cpa_config(timer_param):
    company_code = None
    spider_name = None
    if timer_param != "":
        db_operate = DbOperateClass()
        company_code_sql = "select paramvalue, configname from cpa_config  where configname like '" + timer_param + "' and paramname = 'COMPANY_CODE'"
        data = db_operate.select_one_by_sql(company_code_sql)
        if data is not None:
            company_code = data[0]
        spider_name_sql = "select paramvalue from cpa_config  where configname like '" + timer_param + "' and paramname = 'EXEC_PYTHON_FILE'"
        data = db_operate.select_one_by_sql(spider_name_sql)
        if data is not None:
            spider_name = data[0]
    return company_code, spider_name

if __name__ == '__main__':
    query_from_cpa_timer()
